package com.endbd.systemmanagement.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class DataConverter implements Converter<String, Date> {

  private static final List<String> formats = new ArrayList<>();

  static {
    formats.add("yyyy-MM");
    formats.add("yyyy-MM-dd");
    formats.add("yyyy-MM-dd HH:mm");
    formats.add("yyyy-MM-dd HH:mm:ss");
    formats.add("yyyy/MM");
    formats.add("yyyy/MM/dd");
    formats.add("yyyy/MM/dd HH:mm");
    formats.add("yyyy/MM/dd HH:mm:ss");
  }

  @Override
  public Date convert(String source) {
    String date = source.trim();
    if ("".equals(date)) {
      return null;
    }
    if (source.matches("^\\d{4}-\\d{1,2}$")) {
      return parseDate(source, formats.get(0));
    } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
      return parseDate(source, formats.get(1));
    } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}$")) {
      return parseDate(source, formats.get(2));
    } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
      return parseDate(source, formats.get(3));
    } else if (source.matches("^\\d{4}/\\d{1,2}$")) {
      return parseDate(source, formats.get(4));
    } else if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$")) {
      return parseDate(source, formats.get(5));
    } else if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}$")) {
      return parseDate(source, formats.get(6));
    } else if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
      return parseDate(source, formats.get(7));
    } else {
      throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
    }
  }

  private Date parseDate(String dateStr, String format) {
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat(format);
      return dateFormat.parse(dateStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


}
